from annoying.decorators import render_to
from django.db.models import F
from django.http import Http404
from django.shortcuts import redirect, get_object_or_404
from django.contrib import messages

from core.extensions.decorators import login_required

from core.forms import ParticipationForm
from core.models import Event, User, Participation
from core.views.event.details import details
from core.views.event.strategies_calculation import get_current_sum_for_user
from core.views.event.strategies_calculation import check_patrons


@login_required()
@render_to('event/participation.html')
def change_participation_terms(request, id):
    event = get_object_or_404(Event, id=id)
    user = User.objects.get(id=request.session['user_id'])
    strategy = event.strategy.id
    with_patron = False
    if user not in event.participants.all() \
        or event.status != Event.Status.Scheduled:
        raise Http404()
    participation = Participation.objects.get(user=user, event=event)
    if request.method == 'POST':
        form = ParticipationForm(request.POST)
        if form.is_valid():
            new_investment = form.cleaned_data['investment']
            investment_change = new_investment - participation.investment 
            participation.investment = new_investment
            participation.patron = form.cleaned_data['patron']
            patron = participation.patron
            participation.save()
            event.current_sum = F('current_sum') + investment_change
            strategy = event.strategy.id
            event.current_sum_for_user = get_current_sum_for_user(id, strategy, investment_change, patron)
            event.save()
            messages.info(request, 'participation_terms_changed')
            return redirect(details, id)
    else:
        form = ParticipationForm(instance=participation)
        with_patron = check_patrons(strategy);
    return {'form': form, 'with_patron': with_patron}
